package com.example.imtoken.view.transfer

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.imtoken.R
import com.example.imtoken.core.App
import com.example.imtoken.core.OnBottomSheetDialogFragmentListener
import com.example.imtoken.core.utils.Utils
import com.example.imtoken.databinding.TransferInfoDetailsFragmentBinding
import com.example.imtoken.entitys.app.TransferInfo
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog

class TransferInfoDetailsFragment(private val transferInfo: TransferInfo) :
    BottomSheetDialogFragment() {

    private val viewModel: TransferInfoDetailsViewModel by lazy {
        ViewModelProvider(this).get(TransferInfoDetailsViewModel::class.java)
    }

    private var listener: OnBottomSheetDialogFragmentListener? = null

    private var mLoadingDialog: MiniLoadingDialog? = null

    private var isPwShow = false //密码是否可见

    private var showInputPass = false

    private lateinit var dataBinding: TransferInfoDetailsFragmentBinding

    private var mBehavior: BottomSheetBehavior<View>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //重写样式,设置dialog背景色为透明
        setStyle(STYLE_NORMAL, R.style.AppBottomSheet)
    }

    @SuppressLint("ResourceType")
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
        dataBinding =
            DataBindingUtil.inflate(
                layoutInflater,
                R.layout.transfer_info_details_fragment,
                null,
                false
            )
        dialog.setContentView(dataBinding.root)
        val lp = dataBinding.root.layoutParams
        lp.height = ((ScreenUtils.getAppScreenHeight() * 0.5).toInt()) + BarUtils.getNavBarHeight()
        dataBinding.root.layoutParams = lp
        mBehavior = BottomSheetBehavior.from(dataBinding.root.parent as View)
        initViewContent()
        return dialog
    }

    private fun initViewContent() {
        viewModel.setTransferInfo(transferInfo)
        mLoadingDialog =
            WidgetUtils.getMiniLoadingDialog(
                requireContext(),
                resources.getString(R.string.pleaseWait)
            )
        mLoadingDialog?.setCancelable(true)

        initView()
        initObserve()
        initClick()
    }

    private fun initView() {
        dataBinding.clInputPass.visibility = View.GONE
        dataBinding.clPayDetails.visibility = View.GONE
        if (showInputPass) {
            dataBinding.clInputPass.visibility = View.VISIBLE
        } else {
            dataBinding.clPayDetails.visibility = View.VISIBLE
        }
    }

    private fun initClick() {
        dataBinding.tvConfirm.setOnClickListener {
            val isTransfer = viewModel.checkPassword(dataBinding.etPayPass.text.toString())
            if (isTransfer) {
                viewModel.transfer()
            } else {
                ToastUtils.showShort(R.string.passWordError)
            }
        }
        dataBinding.ivBack.setOnClickListener {
            dismiss()
        }
        dataBinding.tvNext.setOnClickListener {
            showInputPass = true
            initView()
        }
        dataBinding.ivReturn.setOnClickListener {
            KeyboardUtils.hideSoftInput(dataBinding.etPayPass)
            dataBinding.etPayPass.text.clear()
            showInputPass = false
            initView()
        }
        dataBinding.ivShowPass.setOnClickListener {
            dataBinding.etPayPass.clearFocus()
            if (isPwShow) {
                dataBinding.etPayPass.transformationMethod =
                    HideReturnsTransformationMethod.getInstance()
                dataBinding.ivShowPass.setImageResource(R.mipmap.ic_password_show)
            } else {
                dataBinding.etPayPass.transformationMethod =
                    PasswordTransformationMethod.getInstance()
                dataBinding.ivShowPass.setImageResource(R.mipmap.ic_password_no_show)
            }
            isPwShow = !isPwShow
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initObserve() {
        viewModel.getTransferInfo().observe(this) {
            dataBinding.tvAmount.text = "${it.amount} ${it.coin?.toUpperCase()}"
//            dataBinding.tvAmount.text = "${it.amount} ETH"

            dataBinding.tvPayInfo.text =
                getString(R.string.coinTransfer, "${it.coin?.toUpperCase()}")
//            dataBinding.tvPayInfo.text = getString(R.string.coinTransfer, "ETH")
            dataBinding.tvReceivingAddress.text = it.to
            dataBinding.tvPayAddress.text = App.createLiveData.value?.coin?.address
            if (it.coin == "trx") {
                dataBinding.llMinerFeeLayout.visibility = View.GONE
            } else {
                dataBinding.tvMinerFee.text =
                    "${Utils.calculate(it.gas ?: 0, it.gas_price ?: 0, it.pow ?: 0)} ETH"

                dataBinding.tvMinerFeeTips.text =
                    getString(
                        R.string.minerFeeCalculate,
                        it.gas.toString(),
                        "${it.gas_price} ${it.uint}"
                    )
            }
        }
        viewModel.mDialog.observe(this) {
            if (it) {
                mLoadingDialog?.show()
            } else {
                mLoadingDialog?.dismiss()
            }
        }
        viewModel.mErrorStr.observe(this) {
            ToastUtils.showShort(it)
        }
        viewModel.mErrorResId.observe(this) {
            ToastUtils.showShort(it)
        }
        viewModel.isDismiss.observe(this) {
            if (it) {
                dismiss()
            }
        }
        viewModel.isOk.observe(this) {
            if (it) {
                listener?.dialog(this)
            }
        }
    }

    override fun onStart() {
        super.onStart()
        mBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
    }

    fun setOnBottomSheetDialogFragmentListener(onBottomSheetDialogFragmentListener: OnBottomSheetDialogFragmentListener) {
        this.listener = onBottomSheetDialogFragmentListener
    }

}